package com.fy56.platform.logistics.websocket;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fy56.platform.logistics.websocket.cache.SessionCache;
import com.fy56.platform.logistics.websocket.messages.MessageInfoMessage;
import org.apache.catalina.websocket.StreamInbound;
import org.apache.catalina.websocket.WebSocketServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.CharBuffer;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lilianqiang
 */
@WebServlet
public class WebSocketCharServlet extends WebSocketServlet {

    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketCharServlet.class);

    private static final Map<String, SocketConnection> connections = new HashMap<String, SocketConnection>();
    private static final Map<String, String> users = new HashMap<String, String>();

    @Override
    protected StreamInbound createWebSocketInbound(String s, HttpServletRequest httpServletRequest) {
        final String params = httpServletRequest.getParameter("params");
        try {
            String paramsDecoder = java.net.URLDecoder.decode(params, "UTF-8");
            JSONObject jsonObject = JSON.parseObject(paramsDecoder);
            final String ip = jsonObject.getString("ip");
            final String area = jsonObject.getString("area");
            final String userName = jsonObject.getString("userName");
            final String connectionId = jsonObject.getString("sessionId");
            final String tag = jsonObject.getString("tag");

            String state = SessionCache.ValidateAccountLogin(connectionId, userName);

            if ("sameRemoteLogin".equals(state)) {
                SocketConnection connection = SessionCache.getSocketConnection(userName);
                MessageInfoMessage messageInfoMessage = new MessageInfoMessage(userName, userName, "您的帐号在异地" + area + "登录,您已经被踢掉");
                sendMessage(connection, messageInfoMessage);
                SessionCache.connections.remove(connection.getConnectionId());
            } else if ("sameBrowser".equals(state)) {

            }
            if ("haveLogin".equals(state)) {
                //暂时不会在这里处理，前端直接过滤掉了
            }
            return new SocketConnection(connectionId, userName,tag);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }


    protected void sendMessage(SocketConnection connection, MessageInfoMessage messageInfoMessage) {
        try {
            if (connection != null) {
                connection.getWsOutbound().writeTextMessage(CharBuffer.wrap(JSON.toJSONString(messageInfoMessage)));

            }
        } catch (IOException e) {
            LOGGER.error("Impossible to send message", e);
        }
    }


    @Override
    protected boolean verifyOrigin(String origin) {
        return true;
    }
}